
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:robotcontrol/page/video_page/video_controls_widget.dart';
import 'package:video_player/video_player.dart';

class VideoPlayWidget extends StatefulWidget {
  final String url;
  final bool autoPlay;
  final bool looping;
  final bool allowFullScreen;
  final bool allowPalyBaclSpeedChanging;
  final double aspectRatio;

  const VideoPlayWidget(
      {Key key,
      this.url, //视频播放连接
      this.autoPlay = true, //是否自动播放
      this.looping = false, //是否循环播放
      this.allowFullScreen = true, //是否允许全屏播放
      this.aspectRatio = 16 / 9, //视频播放比例
      this.allowPalyBaclSpeedChanging = true

      ///是否允许播放加速
      })
      : super(key: key);

  @override
  VideoPlayState createState() => VideoPlayState();
}

class VideoPlayState extends State<VideoPlayWidget> {
  VideoPlayerController _videoPlayerController ;
  ChewieController _chewieController;

  @override
  void initState() {
    _videoPlayerController = VideoPlayerController.network(widget.url);
    _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController,
        autoPlay: widget.autoPlay,
      looping: widget.looping,
      aspectRatio: widget.aspectRatio,
      allowPlaybackSpeedChanging: widget.allowPalyBaclSpeedChanging,
      allowFullScreen: widget.allowFullScreen,
      //自定义控价
      customControls: VideoControlsWidget(
        overlayUI: _videoPlayTopBar(),
        bottomGradient: _blackLinearGradient(),
      ),
    );
  }
  /// 播放视频的 TopBar
  _videoPlayTopBar(){
    return Container(
      padding: EdgeInsets.only(right: 8),
      // 渐变背景色
      decoration: BoxDecoration(gradient: _blackLinearGradient(fromTop: true)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          BackButton(color: Colors.white),
          Icon(Icons.more_vert_rounded,color: Colors.white,size: 20)
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = width /widget.aspectRatio;
    return Container(
      width: width,
      height: height,
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }
  paly(){
    _chewieController.play();
  }
  pause(){
    _videoPlayerController.pause();
  }

  /// 渐变背景色
  _blackLinearGradient({bool fromTop = false}) {
    return LinearGradient(colors: [
      Colors.black54,
      Colors.black45,
      Colors.black38,
      Colors.black26,
      Colors.black12,
      Colors.transparent
    ],
    begin: fromTop ? Alignment.topCenter:Alignment.bottomCenter,
      end:  fromTop ? Alignment.bottomCenter:Alignment.topCenter,
    );
  }
}
